package com.lyeducation.services.order;

import com.lyeducation.controllers.dto.CartDTO;
import com.lyeducation.controllers.dto.OrderCancelDTO;
import com.lyeducation.controllers.dto.OrderDTO;
import com.lyeducation.converter.OrderMaster2OrderDTOConverter;
import com.lyeducation.core.course.CourseService;
import com.lyeducation.entities.course.CourseEntity;
import com.lyeducation.entities.order.OrderDetail;
import com.lyeducation.entities.order.OrderMaster;
import com.lyeducation.enums.OrderStatusEnum;
import com.lyeducation.enums.PayStatusEnum;
import com.lyeducation.enums.ResultEnum;
import com.lyeducation.exception.LeadingEagleException;
import com.lyeducation.repository.OrderDetailRepository;
import com.lyeducation.repository.OrderMasterRepository;
import com.lyeducation.services.WebSocket;
import com.lyeducation.util.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName UserOrderServiceImpl
 * @Description
 * @Author Sky1in3
 * @Date 2019/1/12 22:14
 * @Version 1.0
 */
@Service
@Slf4j
public class UserOrderServiceImpl implements UesrOrderService {

    @Autowired
    private CourseService courseService;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private WebSocket webSocket;

    /**
     * 创建订单
     */
    @Override
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {
        /** 创建订单id */
        String orderId = KeyUtil.genUniqueKey();

        /** 初始化订单总价 */
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);

        /** 1.查询商品（数量和价格） */
        for (OrderDetail orderDetail : orderDTO.getOrderDetailList()) {
            CourseEntity courseEntity = courseService.findById(orderDetail.getCourseId());
            if (courseEntity == null) {
                throw new LeadingEagleException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            /** 2. 计算订单总价 */
            orderAmount = courseEntity.getCoursePrice()
                    .multiply(new BigDecimal(orderDetail.getCourseQuantity()))
                    .add(orderAmount);

            /** 订单详情入库 */
            orderDetail.setDetailId(KeyUtil.genUniqueKey());
            orderDetail.setOrderId(orderId);
            BeanUtils.copyProperties(courseEntity, orderDetail);
            orderDetail.setCourseName(courseEntity.getName());
            orderDetailRepository.save(orderDetail);
        }

        /** 3. 写入订单数据库（orderMaster和orderDetail） */
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        orderMaster.setOrderId(orderId);
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMasterRepository.save(orderMaster);

        /** 4.扣库存 */
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream().map(e ->
                new CartDTO(e.getCourseId(), e.getCourseQuantity())
        ).collect(Collectors.toList());
        courseService.decreaseStock(cartDTOList);

        /** 发送WebSocket消息 */
        webSocket.sendMessage(orderDTO.getOrderId());

        BeanUtils.copyProperties(orderMaster, orderDTO);
        return orderDTO;
    }

    /**
     * 查询单个订单
     */
    @Override
    public OrderDTO findOne(String buyerOpenid, String orderId) {
        OrderMaster orderMaster = checkOrderOwner(buyerOpenid, orderId);
        if (orderMaster == null) {
            throw new LeadingEagleException(ResultEnum.ORDER_NOT_EXIST);
        }

        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)) {
            throw new LeadingEagleException(ResultEnum.ORDERDETAIL_NOT_EXIST);
        }

        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);

        return orderDTO;
    }

    /**
     * 取消订单
     */
    @Override
    @Transactional
    public OrderCancelDTO cancel(String buyerOpenid, String orderId) {
        OrderMaster orderMaster = checkOrderOwner(buyerOpenid, orderId);

        //判断订单状态
        if (!orderMaster.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【取消订单】订单状态不正确, orderId={}, orderStatus={}", orderMaster.getOrderId(), orderMaster.getOrderStatus());
            throw new LeadingEagleException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //修改订单状态
        orderMaster.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);
        if (updateResult == null) {
            log.error("【取消订单】更新失败, orderMaster={}", orderMaster);
            throw new LeadingEagleException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderMaster.getOrderId());
        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);
        //返回库存
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("【取消订单】订单中无商品详情, orderDTO={}", orderDTO);
            throw new LeadingEagleException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream()
                .map(e -> new CartDTO(e.getCourseId(), e.getCourseQuantity()))
                .collect(Collectors.toList());
        courseService.increaseStock(cartDTOList);

        OrderCancelDTO orderCancelDTO = new OrderCancelDTO();
        BeanUtils.copyProperties(orderDTO, orderCancelDTO);
        //如果已支付, 需要后台审核再进行退款
        if (orderDTO.getPayStatus().equals(PayStatusEnum.SUCCESS.getCode())) {
            //修改支付状态为等待退款
            OrderMaster updatePayStatus = orderMasterRepository.getOne(orderDTO.getOrderId());
            updatePayStatus.setPayStatus(PayStatusEnum.REFUND_WAIT.getCode());
            updatePayStatus = orderMasterRepository.save(updatePayStatus);
            BeanUtils.copyProperties(updatePayStatus, orderCancelDTO);
            orderCancelDTO.setRefundMessage("订单金额将在1~2个工作日退还到您支付的账户上！");
        }
        return orderCancelDTO;
    }

    /**
     * 完结订单
     */
    @Override
    @Transactional
    public OrderDTO finish(String buyerOpenid, String orderId) {
        OrderMaster orderMaster = checkOrderOwner(buyerOpenid, orderId);
        /** 判断订单状态 */
        if (!orderMaster.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【完结订单】订单状态不正确, orderId={}, orderStatus={}", orderMaster.getOrderId(), orderMaster.getOrderStatus());
            throw new LeadingEagleException(ResultEnum.ORDER_STATUS_ERROR);
        }

        /** 修改订单状态 */
        orderMaster.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);
        if (updateResult == null) {
            log.error("【完结订单】更新失败, orderMaster={}", orderMaster);
            throw new LeadingEagleException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(updateResult, orderDTO);
        return orderDTO;
    }

    /**
     * 订单支付
     */
    @Override
    @Transactional
    public OrderDTO paid(OrderDTO orderDTO) {
        /** 判断订单状态 */
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("【订单支付完成】订单状态不正确, orderId={}, orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new LeadingEagleException(ResultEnum.ORDER_STATUS_ERROR);
        }

        /** 判断支付状态 */
        if (!orderDTO.getPayStatus().equals(PayStatusEnum.EXECUTING.getCode())) {
            log.error("【订单支付完成】订单支付状态不正确, orderDTO={}", orderDTO);
            throw new LeadingEagleException(ResultEnum.ORDER_PAY_STATUS_ERROR);
        }

        /** 修改支付状态 */
        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);
        if (updateResult == null) {
            log.error("【订单支付完成】更新失败, orderMaster={}", orderMaster);
            throw new LeadingEagleException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        return orderDTO;
    }

    /**
     * 查询个人订单列表
     */
    @Override
    public Page<OrderDTO> findList(String buyerOpenid, Pageable pageable) {
        Page<OrderMaster> orderMasterPage = orderMasterRepository.findByBuyerOpenid(buyerOpenid, pageable);

        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent());

        return new PageImpl<OrderDTO>(orderDTOList, pageable, orderMasterPage.getTotalElements());
    }

    /**
     * 订单判断
     */
    private OrderMaster checkOrderOwner(String openid, String orderId) {
        if (!orderMasterRepository.existsById(orderId)) {
            return null;
        }
        OrderMaster orderMaster = orderMasterRepository.getOne(orderId);
        //判断是否是自己的订单
        if (!orderMaster.getBuyerOpenid().equalsIgnoreCase(openid)) {
            log.error("【查询订单】订单的openid不一致. openid={}, orderDTO={}", openid, orderMaster);
            throw new LeadingEagleException(ResultEnum.ORDER_OWNER_ERROR);
        }
        return orderMaster;
    }
}
